package com.mlan.userap.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mlan.userap.MyAPP;
import com.mlan.userap.untils.LogHelper;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;

public abstract class JsonCallBack<T> implements Callback {

    private final Type type;

    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    public JsonCallBack() {
        Type superClass = getClass().getGenericSuperclass();
        if (superClass instanceof ParameterizedType) {
            Type rawType = ((ParameterizedType) superClass).getActualTypeArguments()[0];
            // 构造 ApiResponse<T> 的类型 固定
            this.type = TypeToken.getParameterized(ApiResponse.class, rawType).getType();
        } else {
            throw new IllegalArgumentException("CallbackWithGeneric must be parameterized with a type");
        }
    }

    @Override
    public void onFailure(Call call, IOException e) {
        onError(e);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (!response.isSuccessful()) {
            ShowError("服务器错误: " + response.code());
            return;
        }

        ResponseBody body = response.body();
        if (body == null) {
            ShowError("返回数据为空");
            return;
        }

        String json = body.string();
        try {
            LogHelper.i("http:"+json);
            Gson gson = new Gson();
            ApiResponse<T> result = gson.fromJson(json, type);
            if(result.getTag()==0){
                ShowError(result.getMessage());
            }
            else{
                mainHandler.post(() -> onSuccess(result != null ? result : null,json));
            }

        } catch (Exception e) {
            ShowError(e.getMessage());
            mainHandler.post(() -> onError(e));
        }
    }
    public void ShowError(String content) {
        Log.d(OkHttpHelper.TAG, "请求异常：" + content);
      //  Log.e("myApp",content);
        MyAPP.getApp().showToast(content);
    }

    public abstract void onSuccess(ApiResponse<T> result,String value2);

    public abstract void onError(Exception error);
}